package com.hdw.common.base.token;

import com.hdw.common.constant.CommonConstant;
import com.hdw.common.util.TokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //部分方法应忽略token
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(IgnoreToken.class)) {
            return true;
        }
        //获取token
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (null==token) {
            response.sendRedirect("/page/login.html");
            return false;
        }
        return TokenUtil.verifyToken(token,response);
    }
}
